<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/5/4
 * Time: 17:11
 */
namespace app\index\controller\sunfc;

use app\index\controller\Base;
use app\index\controller\Weixin;
use think\Db;
header("Content-type:text/html;charset=utf-8");

class Publish  extends Base
{

    /**
     * 这个是司机的信息
    */

    /**
     * 邀请车主入住首页 ，判断是否入住过 未入住就前去入住,入住过就进入信息界面owner_index
     * URL：index/sunfc.publish/cat_owner
     */
    public function cat_owner(){
        $uid = $this -> uid;
        if(count($uid)>0){
            $data = Db::name('dd_users')
                -> where('uid',$uid)
                ->where('type',2)
                ->where('auth_driver',2)
                -> find();
            if($data){
                // 如果存在就直接重定向去发布信息界面
                $this -> redirect('index/sunfc.publish/owner_index');
            }
            else{
                return  $this -> fetch();
            }
        }
        else{
            return  $this -> fetch();
        }


    }



    /**
     * 这个是用来拿今天发布中待处理 ，司机认证过才可以进来
     * URL：index/sunfc.publish/owner_index (GET)
     *
     */
    public  function  owner_index(){
       $where['driver_id'] = $this -> uid;
        if($where){
            $res = Db::name('dd_publish')
                -> where('uid',$where['driver_id'])
                ->where('is_del',0)
                ->where('status',0)
                ->where('type',2)
                -> find();
            if($res){
                $coun_where['region'] = $res['region'];
                $coun_where['is_del'] = $res['is_del'] ;
                $coun_where['status'] = $res['status'];
                $coun_last = Db::name('dd_publish')
                    -> where($coun_where)
                    ->group('end_place')
                    ->limit(4)
                    -> select();
                $sum = 0;
                foreach ($coun_last as $k => $y){
                    $sum+=  $y['number'];
                }

                    if($res['depart_time']>strtotime(date('Y-m-d',strtotime('day')))){
                        $res['depart_time']="今天".date('H:i',$res['depart_time']);
                    }
                    else{
                        $res['depart_time']= date('m-d H:i',$res['depart_time']);
                }
//                dump($res);
//                dump($sum);
//                dump($coun_last);die();
                    $this->assign('res', $res);
                    $this -> assign('sum',$sum);
                    $this -> assign('coun_last',$coun_last);

            }

            else{
                $res =Db::name('dd_publish_orders')
                    -> where($where)
                    ->alias('d')
                    ->join('dd_users u',"u.uid = d.driver_id and d.status = 0")
                    ->join('dd_publish p',"p.id = d.publish_id")
                    ->field('p.depart_time,p.phone,p.status,p.begin_place,p.begin_detail,
                    p.end_place,p.end_detail,p.number,u.nickname,u.realname,u.headimgurl,
                    u.tel,d.id,d.create_time,p.type,p.region,p.is_del')
                    -> find();
                if($res){
                    $coun_where['region'] = $res['region'];
                    $coun_where['is_del'] = $res['is_del'] ;
                    $where['status'] = $res['status'];
                    $coun_last = Db::name('dd_publish')
                        -> where($coun_where)
                        ->group('end_place')
                        ->limit(4)
                        -> select();
                    $sum = 0;
                    foreach ($coun_last as $k => $y){
                        $sum+=  $y['number'];
                    }


                    if($res['depart_time']>strtotime(date('Y-m-d',strtotime('day')))){
                        $res['depart_time']="今天".date('H:i',$res['depart_time']);
                    }
                    else{
                        $res['depart_time']=  date('m-d H:i',$res['depart_time']);
                    }
                    $q_thumb = "?imageMogr2/auto-orient/thumbnail/!60x120r/gravity/Center/crop/60x60/quality/100/interlace/0";
                    $res['headimgurl'] = $res['headimgurl'] . $q_thumb;
                    $this->assign('res', $res);
                    $this -> assign('sum',$sum);
                    $this -> assign('coun_last',$coun_last);
                    return $this -> fetch();

                }
                else{
                    $res = '';
                    $this->assign('res', $res);
                    return $this -> fetch();
                }
            }
        }
        return $this -> fetch();
    }


    /**
     * 进入信息发布界面
     * * URL：index/sunfc.publish/driver_issue (GET)
    */
    public  function driver_issue(){
        $last['uid'] = $this -> uid;
        $last = input('');
     // dump($last);die();
        session('last',$last);
        $this->assign('last', $last);
        return $this -> fetch();
    }



    /**
     * 这个向数据库中写入数据
     *  URL：index/sunfc.publish/add_issue (post)
     */
    public function  add_issue(){
        if(request()->isPost()){
            $data['uid']                = $this -> uid;             //司机的id
            $user = Db::name('dd_users')
                ->field('tel,openid,realname')
                ->where('uid',$data['uid'])
                ->find();


            //存在的时候向数据库写入数据
            if($user){
                $list = session('last');

                $data['uid']                = $this -> uid;
                $data['phone']              = $user['tel'];                                            // 用户表中的电话
                $data['region']             = $list['region'];                                          // 0本市  1跨市
                $data['type']               = $list['type'];                                            // 1乘客  2司机
                $data['begin_place']        = $list['begin_place'];                                     // 起点
                $data['begin_detail']       = $list['begin_detail'];                                    // 起点详细位置
                $data['end_place']          = $list['end_place'];                                       // 终点
                $data['end_detail']         = $list['end_detail'];                                      // 终点详细位置
                $data['lonlat_begin']       = $list['lonlat_begin'];                                    // 起点的经纬度
                $data['lonlat_end']         = $list['lonlat_end'];                                      // 终点经纬度
                $arr                        = explode("-", input('number_info'));                       // 具体人数说明
                $ck                         =['adult'=>$arr[0],'children'=>$arr[1],'infant'=>$arr[2]];  // 具体人数说明
                $data['number_info']        = json_encode($ck);;                                        // 具体人数说明
                $data['content']            = input('content');                                         // 备注信息
                $year                       =date("Y");                                                 // 拿年进行拼接
                $data['depart_time']        = strtotime($year."-".input('depart_time'));                // 出发时间
                $data['number']             = array_sum(explode("-", input('number_info')));            // 要进行数据处理
                $data['create_time']        = time();


                $sec = Db::name('dd_publish')-> where('uid',$data['uid'])->where('status',0)-> count();
                if($sec > 0){
                    return $this -> error('已经有发布中');
                }



                else{
                    $insert = Db::name('dd_publish') -> insertGetId($data);
                    // 在这个时候是要调用消息模板
                    if($insert){
                        $weixin = new Weixin();
                        $openid = $user['openid'];
//                        $openid         = 'oTJius1s6UiUD2ac02lAO7p0WxXs';
//                        $templete_id    = 'Jxz9iOGhPUiGxX_S-4qzW19aeKY3qDOXhUCMOsARLcU';
                        $rem     =   $this -> getWxTemplate();
                        $re_id=json_decode($rem, true);
                        $templete_id    = $re_id['add_publish'];
                        $url            = request()->domain().'index/sunfc.publish/await_index.html';
                        $data_arr['user_name']          = ['value'=>'亲爱的'.$user['realname'].','.'您的行程已发布，系统正在努力为你寻找顺路乘客，请耐心等待~','color'=>'#ff8a5a'];
                        $data_arr['number']             = ['value'=>$data['number'],'color'=>'#1491cb'];
                        $data_arr['content']            = ['value'=>$data['content'],'color'=>'#1491cb'];
                        $data_arr['depart_time']        = ['value'=>$year."-".input('depart_time'),'color'=>'#1491cb'];
                        $data_arr['begin_detail']          = ['value'=>$data['begin_detail'],'color'=>'#1491cb'];
                        $data_arr['end_detail']        = ['value'=>$data['end_detail'],'color'=>'#1491cb'];
                        if($data['region'] == 1){
                            $data_arr['begin_place']        = ['value'=>$data['begin_place'].$data['begin_detail'],'color'=>'#1491cb'];
                            $data_arr['end_place']          = ['value'=>$data['end_place'].$data['end_detail'],'color'=>'#1491cb'];
                        }
                        $re = $weixin->sentMsg($openid , $templete_id , $url ,$data_arr);
                        if($re['errcode'] != 0){
                            $this->error("错误代码".$re['errcode']);
                        }
                        else{
                            session('last','');
                        }


                        // 重定向到发布成功
                        $this -> redirect('index/sunfc.publish/owner_index');

                    }
                    else{
                        return $this -> error('数据不正确');
                    }
                }
            }


            else{
                // 电话号码没有填写不存在的时候重定向  到填写电话号码界面

               $this -> redirect('');
            }
        }

     }


     /**
      *  等待乘客界面
      * URL：index/sunfc.publish/await_index
      *
      */
    public function await_index(){
        $uid = $this -> uid;
        $list = Db::name('dd_publish')
            ->where('uid',$uid)
            ->where('status',0)
            ->find();
        if($list){
            $this -> assign('list',$list);
            return $this -> fetch();
        }
        else
        {
          $this -> redirect('index/sunfc.publish/owner_index');

        }

    }



    /**
     *   接口是显示同城信息
     * URL：index/sunfc.publish/sameCity
     *
     */
    public function sameCity(){
           $where['region'] = 0;
           $where['is_del'] = 0;
           $where['status'] = 0;
           $last = Db::name('dd_publish')
               -> where($where)
               ->group('end_place')
               ->limit(4)
               -> select();
           $sum = 0;
           foreach ($last as $k => $y){
            $sum+=  $y['number'];
           $last[0]['count'] = $sum;
           }
           $this -> success('ok','',$last);
    }

    /**
     *   这个接口是显示跨城信息
     * URL：index/sunfc.publish/boastCity
     *
     */
    public  function  boastCity(){
        $where['type'] =  1;
        $where['region'] = 1;
        $where['status'] = 0;
        $last = Db::name('dd_publish')
            -> where($where)
            ->where('end_place')
            ->order('id desc')
            ->limit(4)
            -> select();
        $sum = 0;
        foreach ($last as $k => $y){
            $sum+=  $y['number'];
        }
        $last[0]['count'] = $sum;
        $this -> success('ok','',$last);


    }



    /**
     *   行程取消界面
     * URL：index/sunfc.publish/cancel
     *
     */
    public function cancel_index(){
        $id['id'] = input('id');
        if(count($id)){
            $data  =    Db::name('dd_publish') ->where('id',$id['id']) -> find();
            if($data){
                $up = Db::name('dd_publish') ->where('id',$id['id']) -> update(['status'=>3]);
                if($up){
                    $user= Db::name('dd_users')
                        -> where('uid',$this->uid)
                        ->find();
                    $weixin = new Weixin();
                    $openid = $user['openid'];
//          $openid         = 'oTJius1s6UiUD2ac02lAO7p0WxXs';        //用户的openid是获取动态的
                    $rem     =   $this -> getWxTemplate();
                    $re_id=json_decode($rem, true);
                    $templete_id    = $re_id['cancel_publish'];
                    $data_arr['user_name']          = ['value'=>'亲爱的'.$user['realname'].'，你已经成功取消行程','color'=>'#ff8a5a'];
                    $data_arr['begin_place']        = ['value'=>$data['begin_place'].$data['begin_detail'],'color'=>'#1491cb'];
                    $data_arr['end_place']          = ['value'=>$data['end_place'].$data['end_detail'],'color'=>'#1491cb'];
                    $data_arr['depart_time']        = ['value'=>date('Y-m-d H:i:s', time()),'color'=>'#1491cb'];
                    $re = $weixin->sentMsg($openid , $templete_id ,$data_arr);
                    if($re['errcode'] != 0){
                        return $this->error("错误代码".$re['errcode']);
                    }
//                    $this -> redirect('index/sunfc.publish/owner_index');
                    $this -> redirect('cancel_index');
                }
            }
        }




        return  $this ->fetch();

    }




    //附近乘客  本城的页面
    public function nearby_index(){
        $where= input('end_place');

        $last = Db::name('dd_publish')
            ->alias('p')
            ->join('dd_users d','d.uid = p.uid')
            ->field('p.uid,p.begin_detail,p.end_detail,p.depart_time,
            d.realname,d.car_info,d.headimgurl,d.tel,d.sex')
            -> where('end_place',$where)
            ->limit(10)
            -> select();
        foreach ($last as $k=>$v) {

            if ($v['depart_time'] > strtotime(date('Y-m-d', strtotime('day')))) {
                $last[$k]['depart_time'] = "今天" . date('H:i', $v['depart_time']);
            } else {
                $last[$k]['depart_time'] = date('m-d H:i', $v['depart_time']);
            }
        }

        $this -> assign('count',count($last));
        $this -> assign('last',$last);
        $this -> assign('where',$where);
        return $this -> fetch();
    }


    //附近乘客 跨城
    public function different_index(){









    }




    //middle_iindex  是取消过程界面
    public function middle_index(){
       $id = input('id');
       $this -> assign('id',$id);
        return $this -> fetch();
    }








    // 车主行程中
    public function route_index(){
        $order_id = input('order_id');


        if($order_id){
            if(input('order_id')){
//                dump(input('order_id'));
                $trip_data=Db::name('dd_publish_orders')
                    ->join('iw_dd_users','iw_dd_users.uid=iw_dd_publish_orders.passenger_id')
                    ->join('iw_dd_publish','iw_dd_publish_orders.publish_id=iw_dd_publish.id')
                    ->field('iw_dd_users.headimgurl,iw_dd_users.nickname,iw_dd_users.trust_rank,
                iw_dd_users.car_info,iw_dd_users.tel,iw_dd_users.sex,iw_dd_publish_orders.create_time,
                iw_dd_publish_orders.number,iw_dd_publish.begin_place,iw_dd_publish_orders.id,
                iw_dd_publish.begin_detail,iw_dd_publish.end_place,iw_dd_publish.end_detail,
                iw_dd_publish.status,iw_dd_publish.region,iw_dd_publish_orders.status')
                    ->where('iw_dd_publish_orders.id',$order_id)
                    ->find();
//                dump($trip_data);die();
                if($trip_data['create_time']>strtotime(date('Y-m-d',strtotime('day')))){
                    $trip_data['create_time']="今天".date('H:i',$trip_data['create_time']);
                }
                else{
                    $trip_data['create_time']= date('m-d H:i',$trip_data['create_time']);
                }
                $this->assign('trip_data',$trip_data);
                return $this->fetch();
            }
            else{
                $this->redirect(url("index"));
            }

        }
        else{



        }












       return  $this -> fetch();
    }






}
